<template>
    <view class="cart_view">
        <!-- 购物车为空 -->
        <view v-if="cartGoods.length === 0" class="empty-cart">
            <wd-icon name="cart" size="60px" color="#ccc" />
            <text class="empty-text">购物车是空的哦~</text>
        </view>

        <!-- 购物车列表 -->
        <view v-else class="cart-list">
            <view v-for="(category, catIndex) in cartCategories" :key="category.id || catIndex" class="cart-category">
                <!-- 分类标题 -->
                <view class="category-header">
                    <view class="category-selector">
                        <wd-checkbox v-model="category.checked" @change="handleCategoryCheck(catIndex)" shape="circle"
                            class="checkbox-left" />
                        <text class="category-name">{{ category.name }}</text>
                    </view>
                    <wd-button type="text" text-color="#ff4d4f" size="small" @click="handleDeleteCategory(catIndex)"
                        :disabled="!category.goods.some(item => item.checked)">
                        删除分类
                    </wd-button>
                </view>

                <!-- 商品列表 -->
                <view class="category-goods">
                    <view v-for="(item, itemIndex) in category.goods" :key="item.id" class="cart-item">
                        <view class="item-checkbox-col">
                            <wd-checkbox v-model="item.checked" @change="handleItemCheck(catIndex, itemIndex)"
                                shape="circle" class="checkbox-left" />
                        </view>
                        <view class="item-content">
                            <view class="item-info">
                                <image
                                    :src="item.imageUrl || 'https://p0.meituan.net/coverpic/4e9b9e5a742ddfc29f9efb8c7033dbe21323862.jpg'"
                                    class="item-img" />
                                <view class="item-details">
                                    <text class="item-name">{{ item.name }}</text>
                                    <text class="item-price">￥{{ item.price }}</text>
                                </view>
                            </view>
                            <view class="item-quantity">
                                <view class="count-btn count-btn--minus text11" @click="handleCartCountChange(item, -1)"
                                    :class="{ 'count-btn--disabled': item.count <= 1 }">
                                    -
                                </view>
                                <text class="count-btn__num text11">{{ item.count }}</text>
                                <view class="count-btn count-btn--plus text11" @click="handleCartCountChange(item, 1)">
                                    +
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 批量操作 -->
            <view class="batch-operation">
                <view class="select-all-wrap">
                    <wd-checkbox v-model="selectAll" @change="handleSelectAll" shape="circle" class="checkbox-left" />
                    <text class="select-all-text">全选</text>
                </view>
                <wd-button type="error" size="small" @click="handleBatchDelete" :disabled="!hasSelectedItems"
                    class="batch-delete-btn">
                    批量删除
                </wd-button>
            </view>

            <!-- 合计 & 结算 -->
            <!-- <view class="cart-summary">
                <view class="summary-info">
                    <text class="total-text">合计（仅勾选商品）：</text>
                    <text class="total-price">￥{{ cartTotalAmount }}</text>
                </view>
                <wd-button type="primary" class="checkout-btn" :disabled="!hasSelectedItems" @click="handleCheckout">
                    结算
                </wd-button>
            </view> -->

        </view>
    </view>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import Decimal from 'decimal.js'

const props = defineProps({
    cartData: {
        type: Array,
        required: true,
        default: () => []
    }
})

const emit = defineEmits(['update:cartData', 'checkout'])

// 深拷贝处理，避免引用类型问题
const deepClone = (data) => {
    return JSON.parse(JSON.stringify(data))
}

// 内部状态管理
const cartCategories = ref(deepClone(
    props.cartData.map(cat => ({
        ...cat,
        checked: false,
        goods: cat.goods.map(item => ({
            ...item,
            checked: false
        }))
    }))
))

const selectAll = ref(false)

// 计算属性
const cartGoods = computed(() => cartCategories.value.flatMap(c => c.goods))
const hasSelectedItems = computed(() =>
    cartCategories.value.some(cat => cat.goods.some(item => item.checked))
)
const cartTotalAmount = computed(() => totalAmount.value || '0.00')

// 金额计算
const totalAmount = ref('0.00')

// 更新合计（核心修复：正确计算勾选商品）
const updateSelectedTotal = () => {
    let selectedTotal = new Decimal(0)
    cartCategories.value.forEach(cat => {
        // 只计算勾选分类下的勾选商品
        if (cat.checked) {
            cat.goods.forEach(item => {
                if (item.checked && item.count > 0 && !isNaN(Number(item.price))) {
                    selectedTotal = selectedTotal.plus(new Decimal(Number(item.price)).times(item.count))
                }
            })
        }
    })
    totalAmount.value = selectedTotal.toFixed(2)
    emit('total-change', totalAmount.value)
}

// 同步到父组件（修复：确保数据正确传递）
const syncToParent = () => {
    const result = deepClone(cartCategories.value).map(cat => {
        const { checked: _, ...categoryWithoutCheck } = cat
        return {
            ...categoryWithoutCheck,
            goods: categoryWithoutCheck.goods.map(item => {
                const { checked: __, ...itemWithoutCheck } = item
                return itemWithoutCheck
            })
        }
    })
    emit('update:cartData', result)
}

// 数量变更（修复：确保勾选状态正确影响合计）
const handleCartCountChange = (item, delta) => {
    const newCount = item.count + delta
    if (newCount < 1) return

    // 保存当前勾选状态
    const wasChecked = item.checked
    item.count = newCount

    // 同步数据并更新合计
    syncToParent()
    if (wasChecked) {
        updateSelectedTotal()
    }
}

// 分类勾选（修复：全选/取消时正确联动）
const handleCategoryCheck = (idx) => {
    const cat = cartCategories.value[idx]
    // 强制同步商品勾选状态
    cat.goods.forEach(item => {
        item.checked = cat.checked
    })
    // 先更新全选状态再计算合计
    updateSelectAllStatus()
    updateSelectedTotal()
}

// 商品勾选（修复：分类状态联动）
const handleItemCheck = (catIdx, itemIdx) => {
    const cat = cartCategories.value[catIdx]
    // 检查当前分类下所有商品是否都被勾选
    const allChecked = cat.goods.every(item => item.checked)
    // 只有当状态发生变化时才更新（避免无效计算）
    if (cat.checked !== allChecked) {
        cat.checked = allChecked
        updateSelectAllStatus()
    }
    updateSelectedTotal()
}

// 更新全选状态（修复：空列表时状态正确）
const updateSelectAllStatus = () => {
    if (cartCategories.value.length === 0) {
        selectAll.value = false
        return
    }
    selectAll.value = cartCategories.value.every(cat => cat.checked)
}

// 全选操作（修复：状态同步问题）
const handleSelectAll = () => {
    cartCategories.value.forEach(cat => {
        cat.checked = selectAll.value
        cat.goods.forEach(item => {
            item.checked = selectAll.value
        })
    })
    updateSelectedTotal()
}

// 删除分类下勾选商品（修复：索引异常问题）
const handleDeleteCategory = (catIdx) => {
    const cat = cartCategories.value[catIdx]
    if (!cat) return

    const checkedGoods = cat.goods.filter(item => item.checked)
    if (checkedGoods.length === 0) return

    // 删除勾选商品
    cat.goods = cat.goods.filter(item => !item.checked)

    // 若分类无商品则删除分类
    if (cat.goods.length === 0) {
        cartCategories.value.splice(catIdx, 1)
    }

    syncToParent()
    updateSelectedTotal()
    updateSelectAllStatus()
}

// 批量删除（修复：倒序删除避免索引问题）
const handleBatchDelete = () => {
    // 从后往前删除，避免索引错乱
    for (let i = cartCategories.value.length - 1; i >= 0; i--) {
        const cat = cartCategories.value[i]
        const hasChecked = cat.goods.some(item => item.checked)

        if (hasChecked) {
            // 保留未勾选商品
            cat.goods = cat.goods.filter(item => !item.checked)

            // 若分类无商品则删除分类
            if (cat.goods.length === 0) {
                cartCategories.value.splice(i, 1)
            }
        }
    }

    syncToParent()
    updateSelectedTotal()
    updateSelectAllStatus()
}

// 结算处理
const handleCheckout = () => {
    const cleanData = deepClone(cartCategories.value)
        .map(cat => ({
            ...cat,
            goods: cat.goods.filter(item => item.checked).map(item => {
                const { checked, ...rest } = item
                return rest
            })
        }))
        .filter(cat => cat.goods.length > 0)

    emit('checkout', cleanData)
}

// 监听props变化，同步到内部状态
watch(
    () => props.cartData,
    (newVal) => {
        cartCategories.value = deepClone(
            newVal.map(cat => ({
                ...cat,
                checked: false,
                goods: cat.goods.map(item => ({
                    ...item,
                    checked: false
                }))
            }))
        )
        updateSelectAllStatus()
        updateSelectedTotal()
    },
    { deep: true }
)

// 暴露方法
defineExpose({
    setDefaultSelectAll: () => {
        nextTick(() => {
            selectAll.value = true
            handleSelectAll()
        })
    },
    // 新增：获取当前勾选商品的合计金额
    getCartTotalAmount: () => {
        return totalAmount.value || '0.00'
    },

    getSelectedData: () => {
        return deepClone(cartCategories.value)
            .map(cat => ({
                ...cat,
                goods: cat.goods.filter(item => item.checked)
            }))
            .filter(cat => cat.goods.length > 0)
    }
})
</script>

<style lang="less" scoped>
/* 你的样式保持不变 */
@import url("@/static/styles/family/onlineSupermarket/cart-scroll.less");

.cart_view {
    background-color: #fff;
}
</style>